package me.ezitku.base.Sensor

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.fragment.app.Fragment
import com.pawegio.kandroid.sensorManager
import com.ug_project.objects.isNotNull

/**
 * Created by yurqi on 7/1/2017.
 */

fun Context.createSensorListen(action: SensorListener.() -> Unit): Sensor {
    var sensor: Sensor? = null
    sensorManager.isNotNull {
        sensor = it.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        it.registerListener(SensorListener().apply(action), sensor, SensorManager.SENSOR_DELAY_FASTEST)

    }
    return sensor!!
}

fun Fragment.createSensorListen(action: SensorListener.() -> Unit): Sensor {
    return activity!!.createSensorListen(action)
}

fun Context.createSensor(){
    createSensorListen {
        sensorChange {

        }

    }
}

class SensorListener : SensorEventListener {
    internal var _sensorChange: ((SensorEvent) -> Unit)? = null
    var x =0f
    var y =0f
    var z =0f
    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {

    }

    override fun onSensorChanged(event: SensorEvent) {
        x = event.values[0]
        y = event.values[1]
        z = event.values[2]
        _sensorChange?.invoke(event)
    }

    fun sensorChange(action: (SensorEvent) -> Unit) {
        _sensorChange = action
    }
}
